package com.csx.base.design.behavior.mediator;

import java.util.Objects;

/**
 * @author cuisongxu
 * @date 2022/10/11 12:01
 */
public class PublicChatRoom extends ChatRoom{

    public PublicChatRoom(String name) {
        super(name);
    }

    @Override
    protected void register(User user) {
        super.register(user);
        System.out.print("系统消息: 欢迎 【");
        System.out.print(user.getName());
        System.out.println("】 加入公共聊天室 【" + name + "】, 当前人数: " + users.size());

    }

    @Override
    protected void deregister(User user) {
        super.deregister(user);
        System.out.print("系统消息: " + user.getName());
        System.out.println("离开了公共聊天室，当前人数: " + users.size());
    }

    @Override
    protected void sendMsg(User from, User to, String msg) {

        // 不指定消息接收者，则群发
        if(Objects.isNull(to)) {
            users.forEach(user -> user.listen(from, null, msg));
            return;
        }

        // 发送消息给特定的人
        users.stream().filter(user -> user.equals(to) || user.equals(from))
                .forEach(
                user -> user.listen(from, to, msg)
                );
    }



    @Override
    protected String processMsg(User from, User to, String msg) {
        String toName = "所有人";
        if(!Objects.isNull(to)) {
            toName = to.getName();
        }
        return from.getName() + "对 [" + toName + "] 说: " + msg;
    }
}
